package com.yzkj.siot.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yzkj.siot.result.PageParams;
import com.yzkj.siot.result.PageResponse;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PageHelper<T> {

    public PageResponse<T> queryPageOrList(BaseMapper<T> mapper, PageParams<T> pageParams, QueryWrapper<T> wrapper) {
        if (wrapper == null) wrapper = new QueryWrapper<>(pageParams.getEntity());
        int count = mapper.selectCount(wrapper);
        return new PageResponse<>(pageParams, count, pageParams.isAll() ? mapper.selectList(wrapper) : mapper.selectPage(new Page<>(pageParams.getPage(), pageParams.getLimit()), wrapper).getRecords());
    }

    public PageResponse<T> queryPageOrList(IService<T> service, PageParams<T> pageParams, QueryWrapper<T> wrapper) {
        if (wrapper == null) wrapper = new QueryWrapper<>(pageParams.getEntity());
        BaseMapper<T> mapper = service.getBaseMapper();
        int count = mapper.selectCount(wrapper);
        List<T> data;
        if (pageParams.isAll()) {
            data = mapper.selectList(wrapper);
        } else {
            data = mapper.selectPage(new Page<>(pageParams.getPage(), pageParams.getLimit()), wrapper).getRecords();
        }
        return new PageResponse<>(pageParams, count, data);
    }
}
